package com.ryder.subject.infra.basic.utils;

import com.alibaba.druid.filter.config.ConfigTools;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * 描述: 数据库加密util
 *
 * @author Ryder
 * @version 1.0
 * @since 1.0 // 版本号，指明从哪个版本开始
 * 更新日期: 2025/02/03
 */

public class DruidEncryptUtil {
    private static String publicKey;

    private static String privateKey;

    static {
        try {
            String[] keyPair = ConfigTools.genKeyPair(1024);
            privateKey = keyPair[0];
//            System.out.println("privateKey: " + privateKey);
            publicKey = keyPair[1];
            System.out.println("publicKey: " + publicKey);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchProviderException e) {
            throw new RuntimeException(e);
        }
    }

    public static String encrypt(String plainText) throws Exception {
        String encrypt = ConfigTools.encrypt(privateKey, plainText);
//        System.out.println("encrypt: " + encrypt);
        return encrypt;
    }

    public static String decrypt(String cipherText) throws Exception {
        String decrypt = ConfigTools.decrypt(publicKey, cipherText);
//        System.out.println("decrypt: " + decrypt);
        return decrypt;
    }

    public static void main(String[] args) throws Exception {
        String plainText = "r5002362002.";
        String encrypt = encrypt(plainText);
        System.out.println("encrypt: " + encrypt);
        String decrypt = decrypt(encrypt);
        System.out.println("decrypt: " + decrypt);

    }
}
